﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.Application.wbxApplication.Commands.Role
{
    /// <summary>
    /// 角色显示handler
    /// </summary>
    public class SearchRoleHandler : IRequestHandler<SearchRoleCommand, Result<PageResultDto<Roles>>>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 角色
        /// </summary>
        private readonly IBaseRepository<Roles> rolesrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchRoleHandler> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper">mapper</param>
        /// <param name="rolesrepository">rolesrepository</param>
        /// <param name="logger">logger</param>
        public SearchRoleHandler(IMapper mapper, IBaseRepository<Roles> rolesrepository, ILogger<SearchRoleHandler> logger)
        {
            this.mapper = mapper;
            this.rolesrepository = rolesrepository;
            _logger = logger;
        }
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result<PageResultDto<Roles>>> Handle(SearchRoleCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<Roles>>() { Code = (int)CommonErrorCode.Search };
            try
            {
                var page = new PageResultDto<Roles>() { TotalCount = 0, PageCount = 0, List = new List<Roles>() };
                var roles = await (await rolesrepository.GetAll()).ToListAsync();
                if (!string.IsNullOrEmpty(request.RolesName))
                {
                    roles = roles.Where(x => x.RolesName.Contains(request.RolesName)).ToList();
                }
                page.TotalCount = roles.Count();
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.PageSize);
                page.List = roles.OrderBy(x => x.RolesId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = page;
                result.Msg = "角色查询成功";
            }
            catch (Exception ex)
            {
                _logger.LogError("角色查询失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
